package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"service"
	"pojo/form"
	"strconv"
	"pojo/vo"
	"constant"
)

type NewsApi struct {
	service *service.NewsService
}

// 创建NewsApi
func NewNewsApi(service *service.NewsService) *NewsApi {

	return &NewsApi{
		service: service,
	}
}

// 新增新闻信息
func (this *NewsApi) Insert(ctx *gin.Context) {

	newsInfo := &form.NewsForm{}
	ctx.Bind(newsInfo)

	err := this.service.InsertNews(newsInfo)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "保存新闻失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)
}

// 根据id更新新闻信息
func (this *NewsApi) Update(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)

	newsInfo := &form.NewsForm{}
	ctx.Bind(newsInfo)
	newsInfo.Id = id

	err := this.service.UpdateNews(newsInfo)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "保存新闻失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)
}

// 分页查询新闻信息
func (this *NewsApi) List(ctx *gin.Context) {
	query := &form.NewsPageQueryForm{}
	ctx.Bind(query)
	result := this.service.QueryNews(query)
	ctx.JSON(http.StatusOK, result)
}

// 删除新闻信息
func (this *NewsApi) Delete(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)

	err := this.service.DeleteNews(id)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "删除新闻失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)
}

// 根据ID查询新闻信息
func (this *NewsApi) Find(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)

	news, err := this.service.FindNews(id)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "查询新闻失败"
	} else {
		result = constant.SUCCESS
		result.Info = news
	}

	ctx.JSON(http.StatusOK, result)
}
